import { Injectable } from '@angular/core';
import { invoke } from '@tauri-apps/api/tauri';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AppService {

  constructor() {
  }

  listFile(path: string): Observable<any> {
    return new Observable<any>((subscriber) => {
      (async () => {

        let items = await invoke<string[]>('read_dir', {path});
        let files = [];
        for (let f of items) {
          let metadata = await invoke<any>('metadata', {path: f});
          if (metadata['file_type'] !== 'File') continue;
          files.push({
            name: metadata['name'],
            path: f,
            mtime: metadata['modified_time'] * 1000,
          });
        }
        // 按修改时间倒序排序
        files.sort((a: any, b: any) => b.mtime - a.mtime);
        subscriber.next(files);
        subscriber.complete();

      })();
    });

  }

  zip(zipName: string, saveFolder: string, backupFolder: string): Observable<void> {
    return new Observable<void>(subscriber => {

      (async () => {
        let zipPath = `${backupFolder}/${zipName}`;

        invoke('compress_directory', {sourcePath: saveFolder, targetPath: zipPath}).then(() => {
          subscriber.next();
          subscriber.complete();
        }).catch((error) => {
          subscriber.error(error);
        });

      })();

    });
  }

  unzip(zipName: string, saveFolder: string): Observable<void> {
    return new Observable<void>(subscriber => {
      (async () => {


        invoke('delete_directory', {directoryPath: saveFolder}).then(() => {


          invoke('extract_zip', {
            zipPath: zipName,
            targetPath: saveFolder,
          }).then(() => {
            subscriber.next();
            subscriber.complete();
          }).catch((error) => {
            subscriber.error(error);
          });


        }).catch((error) => {
          subscriber.error(error);
        });


      })();
    });
  }
}
